package com.dingpeikeji.quickdeer.modules.wx.member.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.core.modules.sys.service.SystemService;
import com.dingpeikeji.quickdeer.mobile.web.MobileJsonController;
import com.dingpeikeji.quickdeer.modules.utils.ValidateTool;
import com.dingpeikeji.quickdeer.modules.wx.common.web.OAuth;
import com.dingpeikeji.quickdeer.utils.BackResult;
import com.dingpeikeji.quickdeer.utils.JsonUtils;
import com.google.common.collect.Lists;

/**
 * 微信端用户管理
 *
 */
@Controller
@RequestMapping("wx/pu/member")
public class WxUserController extends BaseController{
	
	@Autowired
	private SystemService systemService;
	
	@RequestMapping("info")
	public String info(Model model , HttpServletRequest request) {
		User user = (User)request.getSession().getAttribute(OAuth.SESSION_PUBUSER);
		model.addAttribute("user", user);
		return "wx/modules/member/info";
	}
	
	@RequestMapping(value = "update", method= RequestMethod.POST)
	public String update(User user, HttpServletRequest request, Model model, RedirectAttributes attributes) {
		String view = "redirect:/wx/pu/member/info";
		String name = user.getName();
		String email = user.getEmail();
		List<String> messages = Lists.newArrayList();
		if(ValidateTool.isEmptyOrNull(name)) {
			messages.add("请填写昵称");
		}
		if(StringUtils.isNotEmpty(email)&&!ValidateTool.isEmail(email)) {//邮箱修改为非必填项
			messages.add("请正确填写邮箱");
		}
		if(messages.isEmpty()) {
			User suser = (User)request.getSession().getAttribute(OAuth.SESSION_PUBUSER);
			suser.setName(name);
			suser.setEmail(email);
			model.addAttribute("user", suser);
			systemService.updateUser(suser);
			request.getSession().setAttribute(OAuth.SESSION_PUBUSER,suser);
			addMessage(attributes,"修改信息成功");
			view = "redirect:/wx/pu/my";
		}
		addMessage(attributes,messages.toArray(new String[]{}));
		return view;
	}
}
